#include "dx8_dynamic_image.h"
#include <d3dx8.h>
#include <cassert>

#include "graphics/graphics.h"
#include "graphics/graphics_util.h"
#include "dx8graphics/dx8_graphics.h"

#include "util/timer.h"		    
#include "util/log.h"		    // log
#include "util/common_macros.h"		// macros
#include "util/mmgr.h"	




Dx8DynamicImage ::Dx8DynamicImage (unsigned short Width, unsigned short Height, unsigned short Depth) :
	DynamicImage(Width, Height, Depth),
	m_pTexture(0)
{

}

Dx8DynamicImage ::~Dx8DynamicImage ()
{
	UTIL_SAFE_RELEASE(m_pTexture);
}

bool	Dx8DynamicImage ::CreateTexture()
{
	D3DFORMAT Format = D3DFMT_A8R8G8B8;
	if (m_Depth == 16)	Format = D3DFMT_R5G6B5;
	else if (m_Depth == 24)Format = D3DFMT_R8G8B8;


	HRESULT hRes =
		D3DXCreateTexture(  ((Dx8Graphics*)GetGraphics())->GetDevice(),
		                m_Width,            // width
					    m_Height,           // height
					    1,                  // Mipmap levels
					    D3DUSAGE_DYNAMIC,   // it's a dynamic surface
					    Format,				// 24 bit RGB format
					    D3DPOOL_DEFAULT,    // (D3DPOOL_DEFAULT) default pool, it'll be allocated in VRAM
					    &m_pTexture); // texture
	
    if (FAILED(hRes))
    {
        assert(0 && "Failed to create a dynamic texture");
        _LOG(MSG_ERROR, "Unable to create a " << m_Width << " x " << m_Height << " texture surface for the AVI file");
		return false;
	}

    D3DLOCKED_RECT LockedRegion;
		hRes = m_pTexture->LockRect(0, &LockedRegion, NULL, D3DLOCK_DISCARD);
        assert(SUCCEEDED(hRes) && "Failed to lock texture ");
        memset(LockedRegion.pBits, ColorRGBA(255, 0, 0, 250), LockedRegion.Pitch*m_Height);
    m_pTexture->UnlockRect(0);
	return true;
}

bool	Dx8DynamicImage::CopyBits(COLOR* ColorA)
{
	HRESULT hRes;
    D3DLOCKED_RECT LockedRegion;
		hRes = m_pTexture->LockRect(0, &LockedRegion, NULL, D3DLOCK_DISCARD);
        assert(SUCCEEDED(hRes) && "Failed to lock texture ");
		assert(LockedRegion.Pitch == m_Width*4);
        //memset(LockedRegion.pBits, ColorRGBA(255, 0, 0, 250), LockedRegion.Pitch*m_Height);
		//memcpy(LockedRegion.pBits, ColorA, LockedRegion.Pitch*m_Height);	
		GraphicsUtil::CopyBufferRect(LockedRegion.pBits, ColorA, m_Width, m_Height, LockedRegion.Pitch);
    m_pTexture->UnlockRect(0);
	return true;
}

bool    Dx8DynamicImage::SetTextureStage(unsigned int _TexStage)
{
    if (m_pTexture)
       ((Dx8Graphics*)GetGraphics())->GetDevice()->SetTexture(_TexStage, m_pTexture);
    return true;
}
